package com.ocss.system.service.impl;

import com.ocss.common.core.domain.entity.SysUser;
import com.ocss.common.utils.SecurityUtils;
import com.ocss.system.domain.OcssCourse;
import com.ocss.system.domain.OcssElectiveCourses;
import com.ocss.system.domain.OcssStudent;
import com.ocss.system.mapper.*;
import com.ocss.system.service.IOcssCourseSelectionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class IOcssCourseSelectionServiceImpl implements IOcssCourseSelectionService {


    @Resource
    private OcssCourseSelectionMapper courseSelectionMapper;

    @Resource
    private OcssCourseMapper courseMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private OcssStudentMapper studentMapper;

    @Resource
    private OcssElectiveCoursesMapper electiveCoursesMapper;

    public Long getStudentId() {
        // 获取当前登录的系统用户id
        Long userId = SecurityUtils.getUserId();

        // 根据系统用户id查询 当前学id  pid
        SysUser user = sysUserMapper.selectUserById(userId);

        Long pid = user.getPid();

        return pid;
    }

    // 获取当前登录学生可选课程列表
    @Override
    public List<OcssCourse> selectStudentCourseSelectionList(OcssCourse ocssCourse) {

        Long pid = getStudentId();

        // 0 表示管理员 则返回全部课程
        if (pid == 0) {
            return courseMapper.selectOcssCourseList(ocssCourse);
        }

        // 查询到 该用户的专业，校区 并返回该用户（学生）可选的课程
        OcssStudent ocssStudent = studentMapper.selectOcssStudentById(pid);

        Long professionId = ocssStudent.getProfessionId();
        Long deptId = ocssStudent.getDeptId();

        ocssCourse.setProfessionId(professionId);
        ocssCourse.setDeptId(deptId);

        List<OcssCourse> ocssCourses = courseSelectionMapper.selectStudentCourseSelectionList(ocssCourse);

        return ocssCourses;
    }

    // 抢课逻辑
    @Override
    @Transactional
    public int robClasses(OcssCourse ocssCourse) {

        //  - 根据当前courseId先查course表中course_number是否大于0，
        Long courseId = ocssCourse.getId();

        Long pid = getStudentId();

        // 判断该学生是否已选过此课程 成立的话 返回-2
        OcssElectiveCourses ocssElectiveCourses = new OcssElectiveCourses();
        ocssElectiveCourses.setCourseId(courseId);
        ocssElectiveCourses.setStudentId(pid);

        List<OcssElectiveCourses> electiveCoursesList = electiveCoursesMapper.selectOcssElectiveCoursesList(ocssElectiveCourses);

        if (!electiveCoursesList.isEmpty()) {
            return -2;
        }

        OcssCourse c = courseMapper.selectOcssCourseById(courseId);
        Long remain = c.getRemainingCourses();

        //  - 大于0则向ocss_elective_courses表中添加一条信息---> studentId，courseId，并且将course表中的course_number减去1。
        if (remain > 0) {
            ocssCourse.setRemainingCourses(remain - 1);
            courseMapper.updateOcssCourse(ocssCourse);

            return electiveCoursesMapper.insertOcssElectiveCourses(ocssElectiveCourses);
        }

        //  - 小于或等于0 返回负数

        return -1;
    }

    // 查询已选课列表
    @Override
    public List<OcssCourse> selectStudentCourseSelectedList(OcssCourse ocssCourse) {

        Long studentId = getStudentId();

        OcssElectiveCourses ocssElectiveCourses = new OcssElectiveCourses();
        ocssElectiveCourses.setStudentId(studentId);
        List<OcssElectiveCourses> electiveCoursesList = electiveCoursesMapper.selectOcssElectiveCoursesList(ocssElectiveCourses);

        if (!electiveCoursesList.isEmpty()) {

            Long[] ids = electiveCoursesList.stream()
                    .map(OcssElectiveCourses::getCourseId)
                    .toArray(Long[]::new);

            List<OcssCourse> ocssCourses = courseMapper.selectOcssCourseByIds(ids);

            return ocssCourses;
        }

        List<OcssCourse> emptyList = new ArrayList<>();

        return emptyList;
    }

    // 退课操作
    @Override
    @Transactional
    public int retreat(OcssCourse ocssCourse) {

        // 查出ocss elective courses 表中所需要退的课程 并根据id删除表中的记录
        Long courseId = ocssCourse.getId();
        Long studentId = getStudentId();

        OcssElectiveCourses ocssElectiveCourses = new OcssElectiveCourses();
        ocssElectiveCourses.setStudentId(studentId);
        ocssElectiveCourses.setCourseId(courseId);
        List<OcssElectiveCourses> electiveCoursesList = electiveCoursesMapper.selectOcssElectiveCoursesList(ocssElectiveCourses);

        if (!electiveCoursesList.isEmpty()) {

            // 先判断课程是否结束 或者状态为已结束
            OcssCourse course = courseMapper.selectOcssCourseById(courseId);
            Date courseEndTime = course.getCourseEndTime();
            String status = course.getStatus();

            LocalDate now = LocalDate.now();
            LocalDate endDate = courseEndTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

            if (now.isAfter(endDate) || "3".equals(status)) {
                // 当前时间大于结束日期并且状态为3的逻辑处理
                return -2;
            } else {

                Long[] ids = electiveCoursesList.stream()
                        .map(OcssElectiveCourses::getId)
                        .toArray(Long[]::new);

                int i = electiveCoursesMapper.deleteOcssElectiveCoursesByIds(ids);

                // 将课程表中剩余课程数量+1
                OcssCourse c = courseMapper.selectOcssCourseById(courseId);
                Long remain = c.getRemainingCourses();
                ocssCourse.setRemainingCourses(remain + 1);

                courseMapper.updateOcssCourse(ocssCourse);

                return i;
            }

        }

        return -1;
    }
}
